import request from '@/utils/request'

export default {
  namespaced: true,
  
  state: {
    userInfo: null
  },

  mutations: {
    setUserInfo(state, payload) {
      state.userInfo = payload ? {
        ...payload,
        id: payload._id || payload.id  // 统一ID字段
      } : null
    },
    clearUserInfo(state) {
      state.userInfo = null
    }
  },

  actions: {
    async fetchUserInfo({ commit }) {
      try {
        const res = await request.get('/users/user/info')
        // 深度响应校验
        if (res?.data?.code !== 200 || !res.data.data) {
          throw new Error('无效的响应格式')
        }
        commit('setUserInfo', {
          ...res.data.data,
          id: res.data.data._id // 统一ID字段为id
        })
        return res.data.data
      } catch (error) {
        console.error('[用户信息请求失败]', error)
        if (error.response?.status === 401) {
          uni.removeStorageSync('token') // 清除无效Token
          uni.reLaunch({ url: '/pages/login/login' }) // 跳转登录页
        }
        throw error
      }
    },

    async logout({ commit }) {
      try {
        await request.post('/users/logout')
      } catch (error) {
        console.error('[退出登录失败]', error)
      } finally {
        // 无论成功失败都清除本地状态
        commit('clearUserInfo')
        uni.removeStorageSync('token')
      }
    }
  }
} 